package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.domain.po.Article;
import freemarker.core.Environment;
import freemarker.template.SimpleNumber;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_RIGHTSCOUNT;

/**
 * 自定义标签
 * 曝光和咨询的数量
 *
 * @author chenfangzhou 2018/09/14
 */
@Component
@Slf4j
public class RightsCountDirective extends AbstractDirective {
    @Autowired
    private ArticleServiceClient articleServiceClient;
    /**
     * 站点ID。
     */
    private static final String SITE_ID = "siteId";

    /**
     * 输入参数，分类ID。
     */
    public static final String COLUMN_ID = "columnId";

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            Long siteId = getLong(SITE_ID, params) == null ? (Long) super.getCustomAttrbute(env, SITE_ID) : getLong(SITE_ID, params);
            Long columnId = getLong(COLUMN_ID, params) == null ? (Long) super.getCustomAttrbute(env, COLUMN_ID) : getLong(COLUMN_ID, params);
            Integer rightsCount;
            if (columnId == null) {
                rightsCount = 0;
            } else {
                //曝光和咨询的总条数
                Article articleCount = new Article();
                articleCount.setSiteId(siteId);
                articleCount.setColumnId(columnId);
                rightsCount = articleServiceClient.getRightsCount(articleCount).getData();
            }

            env.setVariable("rightsCount", new SimpleNumber(rightsCount));
            String note = super.getNote(env);
            String userToken = super.getUserToken(env);
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_RIGHTSCOUNT, "");
                    maps.put(SITE_ID, String.valueOf(getLong(SITE_ID, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                log.debug("模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
